﻿using Cofe.Core;
using Cofe.Core.Implements;
using Cofe.Core.Interfaces;
using Cofe.Core.Logger;
using Cofe.Core.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.IO.Implements
{
#if !NETFX_CORE
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEIO)]
    public class SystemIOVolumeFactory : IVolumeFactory
    {

        #region Methods

        public Task<IVolume> ConstructAsync(IVolumeRegistrar volumeRegistrar, string volumeId, string paramString)
        {
            var dic = ParamParser.StringToDictionary(paramString);
            string eventSource = dic.ContainsKey(ParamStringNames.EventSource) ?
                dic[ParamStringNames.EventSource].ToLower() : "auto"; //Auto = use SystemIOWatcherEventSource.                

            var volumeInfo = new VolumeInfo() { FactoryId = FactoryId, ParamString = paramString, VolumeId = volumeId };
            IVolume result = null;

            switch (eventSource)
            {
                case "manual":
                    var manualSource = new ManualCofeSystemEventSource(volumeInfo);
                    result = new Volume(volumeInfo, ParamParser,
                        new SystemIODirectoryLister() { ManualEventSource = manualSource }, manualSource);
                    break;
                case "none":
                    result = new Volume(volumeInfo, ParamParser, new SystemIODirectoryLister());
                    break;
                default:
                    result = new Volume(volumeInfo, ParamParser,
                  new SystemIODirectoryLister(), new SystemIOWatcherEventSource(volumeInfo, ParamParser));
                    break;

            }
            return Task.FromResult<IVolume>(result);

        }
        #endregion

        #region Data

        private IEventHub _eventHub = null;
        private IParamParser _paramParser = new ParamParser();

        #endregion


        #region Public Properties

        public IEventHub EventHub
        {
            get { return _eventHub ?? CofeServices.ServiceLocater.FindService<IEventHub>(); }
            set { _eventHub = value; }
        }

        public IParamParser ParamParser
        {
            get { return _paramParser ?? CofeServices.ServiceLocater.FindService<IParamParser>(); }
            set { _paramParser = value; }
        }


        public string FactoryId
        {
            get { return "CofeIO"; }
        }


        #endregion
    }
#endif
}
